package com.hm.service.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.service.wechat.IWeChatPublic;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

@RestController
@RequestMapping(value = "/MAIN", produces = {"application/json;charset=UTF-8"})
public class WCPS_000_000_001 {
    private static final Logger logger = LoggerFactory.getLogger(WCPS_000_000_001.class);


    private final IWeChatPublic iWeChatPublic;

    public WCPS_000_000_001(IWeChatPublic iWeChatPublic) {
        this.iWeChatPublic = iWeChatPublic;
    }

    //微信网页授权-用code换取openID->作用域为snsapi_base
    @PostMapping(value = "/000_000_001")
    public String doPost(HttpServletRequest request) {
        try {
            String body = request.getReader().readLine();
            JSONObject reqObject = JSONObject.parseObject(body);
            String code = reqObject.getString("code");
            logger.error("code:" + code);
            //本步骤中获取到网页授权access_token的同时，也获取到了openid，snsapi_base式的网页授权流程即到此为止
            return JSON.toJSONString(iWeChatPublic.getOpenid(code));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "";
    }

    //授权链接-作用域为snsapi_base
    public static void main(String[] args) {
        String appID = "wxdd2002c0c548a1e0";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appID
                + "&redirect_uri=" + URLEncoder.encode("http://172.26.2.18:3000/CaseReportV2#/main") //这个是我们回调的地址 在这里进行出来获取到用户的心
                + "&response_type=code"
                + "&scope=snsapi_base"
                + "&state=123#wechat_redirect";
    }


}
